using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Mobileterminal.Common;
using Mobileterminal.Dtos;
using Newtonsoft.Json;
using Sunny.UI;

namespace Mobileterminal.Forms.Yjb
{
    public partial class PendingPrescriptionForm : UIPage
    {
        public PendingPrescriptionForm()
        {
            InitializeComponent();
            LoadPendingPrescriptionDataAsync();
        }

        private async Task LoadPendingPrescriptionDataAsync(string registrationNo = null, string fullName = null)
        {
            try
            {
                // 构建动态查询参数
                var queryParams = new List<string>();
                if (!string.IsNullOrEmpty(registrationNo))
                    queryParams.Add($"registrationNo={Uri.EscapeDataString(registrationNo)}");
                if (!string.IsNullOrEmpty(fullName))
                    queryParams.Add($"fullName={Uri.EscapeDataString(fullName)}");

                var url = "https://localhost:7224/api/Show/ShowPendingPrescription";
                if (queryParams.Count > 0)
                    url += "?" + string.Join("&", queryParams);

                var json = await HttpClientHelper.ClientAsync("GET", url);
                var result = JsonConvert.DeserializeObject<Result<List<PendingPrescriptionDTO>>>(json);

                if (result.Code == 200)
                {
                    // 设置数据源
                    uiDataGridView1.DataSource = result.Data;
                    
                    // 添加操作列
                    if (!uiDataGridView1.Columns.Contains("操作"))
                    {
                        DataGridViewButtonColumn actionColumn = new DataGridViewButtonColumn();
                        actionColumn.Name = "操作";
                        actionColumn.HeaderText = "操作";
                        actionColumn.Text = "打印";
                        actionColumn.UseColumnTextForButtonValue = true;
                        uiDataGridView1.Columns.Add(actionColumn);
                    }
                }
                else
                {
                    UIMessageTip.ShowError($"加载数据失败: {result.Msg}");
                }
            }
            catch (Exception ex)
            {
                UIMessageTip.ShowError($"发生错误: {ex.Message}");
            }
        }

        private async void btnSearch_Click(object sender, EventArgs e)
        {
            string registrationNo = txtRegistrationNo.Text.Trim();
            string fullName = txtFullName.Text.Trim();
            await LoadPendingPrescriptionDataAsync(registrationNo, fullName);
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            txtRegistrationNo.Text = string.Empty;
            txtFullName.Text = string.Empty;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            txtRegistrationNo.Text = string.Empty;
            txtFullName.Text = string.Empty;
            LoadPendingPrescriptionDataAsync();
        }

        private async void uiDataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex == uiDataGridView1.Columns["操作"].Index)
            {
                int pendingPrescriptionId = Convert.ToInt32(uiDataGridView1.Rows[e.RowIndex].Cells["PendingPrescriptionId"].Value);
                string registrationNo = uiDataGridView1.Rows[e.RowIndex].Cells["RegistrationNo"].Value.ToString();
                string fullName = uiDataGridView1.Rows[e.RowIndex].Cells["FullName"].Value.ToString();
                string genderType = uiDataGridView1.Rows[e.RowIndex].Cells["GenderType"].Value.ToString();
                int ageValue = Convert.ToInt32(uiDataGridView1.Rows[e.RowIndex].Cells["AgeValue"].Value);
                string idCardNo = uiDataGridView1.Rows[e.RowIndex].Cells["IdCardNo"].Value.ToString();

                // 更新记录为已打印
                var updateData = new
                {
                    PendingPrescriptionId = pendingPrescriptionId,
                    RegistrationNo = registrationNo,
                    FullName = fullName,
                    GenderType = genderType,
                    AgeValue = ageValue,
                    IdCardNo = idCardNo,
                    CreateTime = DateTime.Now,
                    PrintFlag = true,
                    IsDeleted = false
                };

                var content = new StringContent(
                    JsonConvert.SerializeObject(updateData),
                    Encoding.UTF8,
                    "application/json");

                try
                {
                    var json = await HttpClientHelper.ClientAsync("PUT", "https://localhost:7224/api/Yjb/UpdatePendingPrescription", false, content);
                    var result = JsonConvert.DeserializeObject<Result<int>>(json);
                    
                    if (result.Code == 200)
                    {
                        UIMessageTip.ShowOk("打印成功！");
                        // 刷新数据
                        await LoadPendingPrescriptionDataAsync();
                        
                        // 添加到处方查看表
                        var addCheckData = new
                        {
                            RegistrationNumber = registrationNo,
                            PatientName = fullName,
                            Gender = genderType,
                            Age = ageValue,
                            IdNumber = idCardNo,
                            CardNumber = registrationNo,  // 假设卡号与挂号编号相同，根据实际情况调整
                            IsPrinted = false,
                            IsMedicineProvided = false,
                            IsDeleted = false
                        };

                        content = new StringContent(
                            JsonConvert.SerializeObject(addCheckData),
                            Encoding.UTF8,
                            "application/json");

                        json = await HttpClientHelper.ClientAsync("POST", "https://localhost:7224/api/Yjb/AddPrescriptionCheck", false, content);
                        result = JsonConvert.DeserializeObject<Result<int>>(json);
                        
                        if (result.Code != 200)
                        {
                            UIMessageTip.ShowError($"添加到处方查看表失败: {result.Msg}");
                        }
                    }
                    else
                    {
                        UIMessageTip.ShowError($"打印失败: {result.Msg}");
                    }
                }
                catch (Exception ex)
                {
                    UIMessageTip.ShowError($"发生错误: {ex.Message}");
                }
            }
        }
    }

    public class PendingPrescriptionDTO
    {
        public int PendingPrescriptionId { get; set; }
        public string RegistrationNo { get; set; }
        public string FullName { get; set; }
        public string GenderType { get; set; }
        public int AgeValue { get; set; }
        public string IdCardNo { get; set; }
        public DateTime CreateTime { get; set; }
        public bool PrintFlag { get; set; }
        public bool IsDeleted { get; set; }
    }
} 